provider "alicloud" {
  region = "cn-hangzhou"
}

//根据资源组名称查询资源组
data "alicloud_resource_manager_resource_groups" "rmrg" {
  name_regex = var.resource_group_id
}

//根据资源组id查询vpc
data "alicloud_vpcs" "vpcs2" {
  resource_group_id = data.alicloud_resource_manager_resource_groups.rmrg.groups.0.id
}

//根据资源组id查询vswitch
data "alicloud_vswitches" "vsws" {
  resource_group_id = data.alicloud_resource_manager_resource_groups.rmrg.groups.0.id
}

//根据vpc id查询安全组
data "alicloud_security_groups" "sgs" {
  vpc_id = data.alicloud_vpcs.vpcs2.vpcs.0.id
}

//创建密钥对
resource "alicloud_ecs_key_pair" "ekp" {
  key_pair_name = var.key_name
  public_key    = var.public_key
  resource_group_id = data.alicloud_resource_manager_resource_groups.rmrg.groups.0.id
}

//创建instance
//必须指定资源组，否则创建后资源组子帐号无法管理
resource "alicloud_instance" "middleware" {
  availability_zone = var.availability_zone
  security_groups = data.alicloud_security_groups.sgs.groups.*.id
  # series III
  instance_type        = var.instance_type
  image_id             = var.image_id
  instance_name        = var.instance_name
  vswitch_id = data.alicloud_vswitches.vsws.vswitches.0.id
  internet_max_bandwidth_out = 0
  key_name   = alicloud_ecs_key_pair.ekp.key_pair_name
  resource_group_id = data.alicloud_resource_manager_resource_groups.rmrg.groups.0.id
}

// 为每个计算资源创建一个对应的 ansible_host 资源，
// 执行 ansible playbook 前会基于 ansible_host 资源自动生成 inventory 文件。
resource "ansible_host" "middleware" {
//  count = var.instance_number

  // 配置机器的 hostname，一般配置为计算资源的 public_ip (或 private_ip)
  inventory_hostname = alicloud_instance.middleware.private_ip

  // 配置机器所属分组
  groups = ["middleware"]

  // 传给 ansible 的 vars，可在 playbook 文件中引用
  vars = {
    wait_connection_timeout = 600
    private_ip = alicloud_instance.middleware.private_ip
    mysql=var.mysql
    consul=var.consul
    docker_pw=var.docker_pw
    mysql_root_user=var.mysql_root_user
    mysql_root_pw=var.mysql_root_pw
  }
}

output "private_ip" {
   value = alicloud_instance.middleware.private_ip
}